<script setup lang="ts">
import { ref, defineProps, defineEmits, withDefaults, watch,onMounted } from "vue";
import { ElMessage } from "element-plus";
import { addProductApi } from "@/api/products/product";
// 导入图片上传组件
import UploadImg from '@/views/components/uploads/uploadImg.vue';
import { getProductKeys } from "@/utils/appCommon/appCommonOptions/products";
import { useI18n } from "vue-i18n";

// 初始化i18n
const { t } = useI18n();

// 定义props
const props = withDefaults(defineProps<{
  visible: boolean;
}>(), {
  visible: false
});

// 添加本地对话框状态
const dialogVisible = ref(props.visible);

// 监听prop变化同步到本地状态
watch(
  () => props.visible,
  (newVal) => {
    dialogVisible.value = newVal;
  },
  { immediate: true }
);

// 监听本地状态变化通知父组件
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
  (e: 'success'): void;
}>();

// 表单数据
const formData = ref<{
  name: string,
  productKey: string,
  type: number,
  description: string,
  remark: string,
  image: string,
  version: string,
  openStatus: number
}>({
  name: '',
  productKey: '',
  type: 0,
  description: '',
  remark: '',
  image: '',
  version: '',
  openStatus: 0
});

// 设备类型选项
const deviceTypeOptions = [
  { val: 0, label: t('products.productPage.directDevice') },
  { val: 1, label: t('products.productPage.gatewayDevice') },
  { val: 2, label: t('products.productPage.subDevice') }
];

// 激活状态选项
const statusOptions = [
  { val: 0, label: t('products.productPage.inactive') },
  { val: 1, label: t('products.productPage.active') }
];

const productKeys = ref([])

onMounted(async () => {
  productKeys.value = await getProductKeys()
})

// 提交表单
const submitForm = async () => {
   try {
    const submitData = {
      productKey: formData.value.productKey,
      name: formData.value.name,
      type: formData.value.type,
      description: formData.value.description,
      remark: formData.value.remark,
      image: formData.value.image,
      version: formData.value.version,
      openStatus: formData.value.openStatus
    };

    const response = await addProductApi(submitData);
    if (response.code === 0) {
      ElMessage.success(t('products.productPage.addSuccess'));
      emit('update:visible', false);
      emit('success');
      resetForm();
    } else {
      ElMessage.error(response.msg || t('products.productPage.addFailed'));
    }
  } catch (error) {
    ElMessage.error(t('products.productPage.addFailed'));
    console.error('Failed to add product:', error);
  }
};

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    productKey: '',
    type: 0,
    description: '',
    remark: '',
    image: '',
    version: '',
    openStatus: 0
  };
};

// 关闭弹框
const closeDialog = () => {
  emit('update:visible', false);
  emit('close');
};

const handleImgChange = (e:any)=> {
  console.log(e)
  formData.value.image = e
}

</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('products.productPage.addProduct')"
    :draggable="true"
    @close="closeDialog"
  >
    <el-form
      :model="formData"
      style="max-width: 600px; margin: 0 auto;"
    >
      <el-form-item :label="t('products.productPage.productName')" prop="name" required>
        <el-input v-model="formData.name" :placeholder="t('products.productPage.enterProductName')" />
      </el-form-item>
      <el-form-item :label="t('products.productPage.productKey')" prop="productKey" required>
        <el-select v-model="formData.productKey" :placeholder="t('products.productPage.selectProductKey')">
          <el-option
            v-for="option in productKeys"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.productPage.deviceType')" prop="type" required>
        <el-select v-model="formData.type" :placeholder="t('products.productPage.selectDeviceType')">
          <el-option
            v-for="option in deviceTypeOptions"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.productPage.productDescription')" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          :placeholder="t('products.productPage.enterProductDescription')"
        />
      </el-form-item>
      <el-form-item :label="t('products.productPage.productVersion')" prop="version">
        <el-input v-model="formData.version" :placeholder="t('products.productPage.enterProductVersion')" />
      </el-form-item>
      <el-form-item :label="t('products.productPage.activationStatus')" prop="openStatus">
        <el-select v-model="formData.openStatus" :placeholder="t('products.productPage.selectActivationStatus')">
          <el-option
            v-for="option in statusOptions"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('products.productPage.remark')" prop="remark">
        <el-input v-model="formData.remark" :placeholder="t('products.productPage.enterRemark')" />
      </el-form-item>
      <el-form-item :label="t('products.productPage.image')" prop="image" required>
        <upload-img v-model:imgUrl="formData.image" @change="handleImgChange" />
        <div class="upload-hint">{{ t('products.productPage.uploadImageHint') }}</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">{{ t('buttons.reset') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t('buttons.submit') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
// 可以添加一些自定义样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.upload-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>
